<template>
	<div class="demand-monitoring">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/' }">
				<i class="lh lh-diaodu fw_100"></i>
			</el-breadcrumb-item>
			<el-breadcrumb-item>调度中心</el-breadcrumb-item>
			<el-breadcrumb-item>店铺需求监控</el-breadcrumb-item>
		</el-breadcrumb>

		<div class="content_Box box-shadow">
			<div class="py_5 px_10">
				<el-row>
					<el-col :span="4" class="fl">
						<el-button round size="mini" @click="download">导出</el-button>
					</el-col>
					<el-col :span="20" class="fr">
						<el-form :inline="true" :model="ruleForm" class="form-inline fr" @keyup.enter.native="shearchBtn()">
							<el-form-item>
								<el-autocomplete
									size="mini"
									class="w_150"
									v-model="ruleForm.shop_name"
									:fetch-suggestions="querySearch"
									placeholder="请选择店铺名称"
									:trigger-on-focus="true"
									@select="handleSelect"
								></el-autocomplete>
							</el-form-item>
							<lh-agent-list @sendValue="setValue" :reset="agent_reset"></lh-agent-list>
							<el-form-item class="w_140">
								<el-select v-model="ruleForm.city_id" placeholder="城市" @change="changeSelectCity">
									<el-option v-for="item in cityList" :key="item.id" :label="item.name" :value="item.id"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item class="w_180">
								<!-- <el-select v-model="ruleForm.area_id" clearable filterable placeholder="商圈">
									<el-option
										v-for="item in areaList"
										:key="item.id"
										:label="item.area_name"
										:value="item.id"
									></el-option>
								</el-select> -->
								<el-select v-model="area_arr" multiple collapse-tags placeholder="商圈">
									<el-button
										size="mini"
										type="primary"
										class="round-right all-area"
										@click="selectAllArea()"
										native-type="button"
										>{{ areaStatus ? '全选' : '取消全选' }}</el-button
									>
									<el-option
										v-for="item in areaList"
										:key="item.id"
										:label="item.area_name"
										:value="`${item.id}|${item.area_name}`"
									></el-option>
								</el-select>
							</el-form-item>
							<el-form-item prop="datetime3">
								<el-date-picker
									:clearable="false"
									size="mini"
									type="date"
									class="w_120i"
									value-format="yyyy-MM-dd"
									placeholder="日期"
									v-model="ruleForm.date"
								></el-date-picker>
							</el-form-item>
							<el-button size="mini" type="primary" class="round-right" native-type="button" @click="shearchBtn"
								>搜索</el-button
							>
							<el-button size="mini" round @click="resetBtn">重置</el-button>
						</el-form>
					</el-col>
				</el-row>
			</div>
			<div class="monitor-types">
				<el-button
					size="mini"
					v-for="it in LABELS"
					:key="it.key"
					:label="it.text"
					:value="it.key"
					@click="changeMonitorType(it.key)"
					:type="ruleForm.type === it.key ? it.tag : 'default'"
					class="button"
				>
					{{ it.text }}
					<span>({{ it.count }})</span>
				</el-button>
			</div>
			<div class="tableMaxBox">
				<template>
					<!-- 表格部分 -->
					<el-table :data="demandList" stripe>
						<el-table-column type="index" prop="id" label="序号" width="50px" align="center"></el-table-column>
						<el-table-column label="店铺名称" width="150">
							<template slot-scope="{ row }">
								<el-tooltip class="list-tooltip" effect="light" placement="right">
									<div slot="content">
										<div>店铺负责人: {{ row.contact }}{{ row.contact_phone }}</div>
										<div class="mt_10">BD: {{ row.business_director }}{{ row.business_phone }}</div>
									</div>
									<el-link type="primary" @click="shopLists(row)" :underline="false">
										{{ row.shop_name }}<span class="new-shop ml_10" v-if="row.new_shop == 1">新</span>
									</el-link>
								</el-tooltip>
							</template>
						</el-table-column>
						<el-table-column prop="area_name" label="商圈" width="120" align="center">
							<template slot-scope="{ row }">
								<span type="primary">{{ row.area_name }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="task_num" label="已发任务数" width="120" align="center">
							<template slot-scope="{ row }">
								<span v-if="row.task_num == 0">{{ row.task_num }}</span>
								<el-tooltip effect="light" v-else placement="top" :open-delay="500">
									<div slot="content">
										<div style="margin-bottom: 20px;">
											<span class="mr_10 mb_20">{{ row.theDate }}</span>
											<span class="mr_10 mb_20">已发任务数：{{ row.task_num }}</span>
										</div>
										<div style="margin-bottom: 20px;" v-for="(item, index) in taskList" :key="index">
											<span class="mr_10 mb_20">{{ item.start_time }}-{{ item.end_time }}</span>
											<span class="mr_10 mb_20" style="color: var(--blue1); text-decoration: underline;"
												>{{ item.period }}人</span
											>
											<span class="mb_20">{{ item.status }}</span>
										</div>
									</div>

									<div @mouseover="cellMouseEnterSD(row)" @mouseout="cellMouseEnterOut" @click="goTaskList(row)">
										<div>
											<h4 class="under-person-num">{{ row.task_num }}</h4>
										</div>
									</div>
								</el-tooltip>
							</template>
						</el-table-column>

						<el-table-column prop="theDate" label="日期" width="150" align="center"></el-table-column>
						<el-table-column prop="type" label="预警类型" width="100" align="center">
							<template slot-scope="{ row }">
								<span class="text-success" v-if="row.type == '1'">应下已下</span>
								<span class="text-danger" v-if="row.type == '2'">应下未下</span>
								<span class="text-success" v-if="row.type == '3'">已下</span>
							</template>
						</el-table-column>
						<el-table-column prop="last_work_time" label="最后用工日期" width="160" align="center"></el-table-column>
						<el-table-column prop="reason_type_name" label="原因类型" width="120" align="center"></el-table-column>
						<el-table-column prop="reason_name" label="不用工原因" width="120" align="center"></el-table-column>
						<el-table-column prop="remark" label="备注" width="120" align="center"></el-table-column>

						<el-table-column label="操作" min-width="120px" fixed="right" align="center">
							<template slot-scope="{ row }">
								<span class="cursor text-success" @click="goAddOrder(row)">去下单</span>
								<span v-if="row.type == 2 && ruleForm.type == 2">｜</span>
								<span v-if="row.type == 2 && ruleForm.type == 2" class="cursor text-warning" @click="record(row)"
									>记录</span
								>
							</template>
						</el-table-column>
					</el-table>
					<!-- 分页组件 -->
					<page :total="total" :pageNums="pageNum" @pagedata="onChildValue" :disableMountedFetch="true"></page>
				</template>
			</div>
		</div>

		<el-dialog title="异常记录" :visible.sync="exceptionRecordShow" width="800px" :before-close="cancelEecord">
			<div>
				<el-row class="dialog-layout" :gutter="20">
					<el-col :span="8">
						<div class="flex-container">
							<div class="label-name">店铺名称：</div>
							<div>{{ workRecord.shop_name }}</div>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="flex-container">
							<div class="label-name">店铺负责人：</div>
							<div>{{ workRecord.contact }}</div>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="flex-container">
							<div class="label-name">手机号：</div>
							<div>{{ workRecord.contact_phone }}</div>
						</div>
					</el-col>
				</el-row>
				<el-row class="dialog-layout" :gutter="20">
					<el-col :span="8">
						<div class="flex-container">
							<div class="label-name">所在商圈：</div>
							<div>{{ workRecord.area_name }}</div>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="flex-container">
							<div class="label-name">销售：</div>
							<div>{{ workRecord.business_director }}</div>
						</div>
					</el-col>
					<el-col :span="8">
						<div class="flex-container">
							<div class="label-name">手机号：</div>
							<div>{{ workRecord.business_phone }}</div>
						</div>
					</el-col>
				</el-row>
				<el-row class="dialog-layout mt_10" :gutter="20">
					<el-col :span="24">
						<div class="flex-container">
							<div class="label-name">监控用工日期：</div>
							<div>{{ workRecord.theDate }}</div>
						</div>
					</el-col>
				</el-row>
				<el-row class="dialog-layout" :gutter="20">
					<el-col :span="24">
						<div class="flex-container">
							<div class="label-name"><i class="lhadmin lhadmin-wujiaoxing"></i>不用工原因：</div>
							<div>
								<el-select v-model="abnormal.reason_type" clearable placeholder="请选择" @change="reasonChange">
									<el-option v-for="item in reasonList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
								</el-select>
								<el-select v-model="abnormal.reason_id" clearable placeholder="请选择">
									<el-option v-for="item in reasonSubsetList" :key="item.id" :label="item.name" :value="item.id">
									</el-option>
								</el-select>
							</div>
							<div class="text-gray">说明：客观原因不影响下次推荐</div>
						</div>
					</el-col>
				</el-row>

				<el-row class="dialog-layout" :gutter="20">
					<el-col :span="24">
						<div class="flex-container">
							<div class="label-name">不用工日期：</div>
							<div class="flex-container">
								<el-date-picker
									v-model="abnormal.start_date"
									type="date"
									placeholder="选择日期"
									format="yyyy-MM-dd"
									value-format="yyyy-MM-dd"
									:picker-options="pickerOptions"
								>
								</el-date-picker>
								<span class="mr_10">至</span>
								<el-date-picker
									v-model="abnormal.end_date"
									type="date"
									placeholder="选择日期"
									format="yyyy-MM-dd"
									value-format="yyyy-MM-dd"
									:picker-options="pickerOptions"
								>
								</el-date-picker>
							</div>
						</div>
					</el-col>
				</el-row>
				<el-row class="dialog-layout mt_10" :gutter="20">
					<el-col :span="20">
						<div class="flex-container">
							<div class="label-name">备注：</div>
							<el-input
								type="textarea"
								:rows="4"
								maxlength="100"
								show-word-limit
								placeholder="请输入内容"
								v-model="abnormal.remark"
							>
							</el-input>
						</div>
					</el-col>
				</el-row>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="cancelEecord">取 消</el-button>
				<el-button type="primary" @click="saveEecord()">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
var common = require('../../../static/tool.js')

import {
	fetchShopList,
	fetchAreaList,
	fetchShopDemandMatch,
	fetchReasonList,
	queryTaskList,
	demandSetRecord
} from '@/api/shop.js'
import { getWeekday, TASK_STATUS } from '@/utils/util.js'
import dayjs from 'dayjs'
export default {
	name: 'ShopMonitoring',
	data() {
		return {
			pickerOptions: {
				disabledDate(time) {
					return time.getTime() < Date.now()
				}
			},
			url: common.url,
			exceptionRecordShow: false,
			//搜索对应值
			ruleForm: {
				shop_name: '', //店铺名
				shop_id: '', //店铺id
				shop_sn: '', //店铺sn
				area_id: '',
				area_name: '',
				type: '2', //类型
				date: '',
				city_id: '',
				agent_id: ''
			},
			cityList: [], //城市
			demandList: [], //店铺列表
			//向分页组件传值
			total: 0,
			pageNum: 1,
			pageSizeNow: 20,
			areaList: [], //区域列表
			shopList: [], //店铺列表
			LABELS: [
				{
					key: '2',
					text: '未下单',
					tag: 'danger',
					count: 0
				},
				{
					key: '1',
					text: '已下单',
					tag: 'success',
					count: 0
				},
				{
					key: '',
					text: '全部',
					tag: 'primary',
					count: 0
				}
			],
			abnormal: {
				reason_id: '',
				reason_type: '',
				start_date: '',
				end_date: '',
				remark: ''
			},
			workRecord: {}, //记录
			reasonList: [], //记录不用工原因
			reasonSubsetList: [],
			taskList: [],
			agent_reset: 0,
			area_arr: [],
			areaStatus: true
		}
	},
	created() {
		this.ruleForm.date = this.date(1)
	},
	mounted() {
		this.fetchReasonList()
	},
	watch: {
		'ruleForm.shop_name'(val) {
			if (!val) {
				this.ruleForm.shop_id = ''
				this.ruleForm.shop_sn = ''
			}
		}
	},
	methods: {
		async setValue(data) {
			this.ruleForm.agent_id = data.agent_id

			//清空店铺名称
			this.ruleForm.shop_name = ''

			this.cityList = data.city_list
			if (this.cityList.length > 0) {
				this.ruleForm.city_id = this.cityList[0].id
			}
			await this.changeSelectCity()
			await this.fetchShopList()
			this.fetchMonitorList()
		},
		date(e) {
			return this.$moment().add('days', e).format('YYYY-MM-DD')
		},
		async fetchReasonList() {
			try {
				let res = await fetchReasonList()
				this.reasonList = res
			} catch (err) {
				console.log(err)
			}
		},
		reasonChange(val) {
			if (!val) {
				this.reasonSubsetList = []
				this.abnormal.reason_id = ''
				return
			}
			this.reasonSubsetList = this.reasonList.find(x => x.id == val).list
		},

		async changeSelectCity() {
			try {
				let ret = await fetchAreaList({
					city_id: this.ruleForm.city_id,
					agent_id: this.ruleForm.agent_id
				})
				ret.list.forEach(element => {
					//去除 平谷和无商圈
					if (element.area_name != '平谷' && element.id != 0) {
						var pusharr = element.id + '|' + element.area_name
						// this.area_arr.push(pusharr)
					}
				})

				this.areaList = ret.list
				this.ruleForm.area_id = ''

				//清空店铺名称
				this.ruleForm.shop_name = ''
				this.fetchShopList()
			} catch (err) {
				console.log(err)
			}
		},

		changeMonitorType(type) {
			this.ruleForm.type = type
			this.pageNum = 1
			this.fetchMonitorList()
		},

		// 获取店铺列表
		async fetchShopList() {
			try {
				let ret = await fetchShopList({
					// 店铺: 已合作
					sign_status: 30,
					// 店铺: 启用
					status: 1,
					agent_id: this.ruleForm.agent_id,
					city_id: this.ruleForm.city_id
				})

				ret.list.forEach(item => {
					item.value = item.name
				})
				this.shopList = ret.list
			} catch (err) {
				console.log('err: ', err)
			}
		},
		// 获取需求监控列表
		async fetchMonitorList() {
			try {
				let area_id = []
				this.area_arr.forEach(element => {
					let [id, name] = element.split('|')
					area_id.push(id.toString())
				})
				this.ruleForm.area_id = area_id.join(',')

				let ret = await fetchShopDemandMatch({
					pageSize: this.pageSizeNow,
					page: this.pageNum,
					...this.ruleForm
				})
				ret.list.forEach(it => {
					if (it.last_work_time == '0000-00-00 00:00:00') it.last_work_time = ''
					it.apply_time = dayjs(it.apply_time).format('YYYY-MM-DD')
					let weeks = getWeekday(dayjs(it.apply_time).format('d'))
					it.theDate = it.apply_time + ' (' + weeks + ')'
				})

				this.LABELS.forEach(it => {
					if (+it.key === 2) {
						it.count = ret.countAll.no
					} else if (+it.key === 1) {
						it.count = ret.countAll.yet
					} else {
						it.count = ret.countAll.all
					}
				})

				this.demandList = ret.list
				this.total = ret.count
			} catch (err) {
				console.log(err)
			}
		},

		//导出订单
		download() {
			let obj = {
				token: JSON.parse(sessionStorage.getItem('manageInfo')).token,
				operation: 'export',
				...this.ruleForm
			}
			let param = $.param(obj)
			window.location.href = this.url + '/abnormal/shopDemandMatch?' + param
		},

		async cellMouseEnterSD(row, column, cell, event) {
			try {
				let ret = await queryTaskList({
					shop_id: row.shop_id,
					area_id: row.area_id,
					status: [10, 20, 30, 40, 50, 60, 70, 80].join(','),
					time_type: 2,
					start_time: this.$moment(this.ruleForm.date).format('yyyy-MM-DD') + ' 00:00:00',
					end_time: this.$moment(this.ruleForm.date).format('yyyy-MM-DD') + ' 23:59:59',
					hideLoading: true
				})
				this.taskList = ret.list.map(it => {
					return {
						start_time: it.start_time,
						end_time: it.end_time,
						period: it.period,
						status: TASK_STATUS[it.status]
					}
				})
			} catch (err) {
				console.log('获取应发已发任务数报错: ', err)
				this.taskList = []
			}
		},

		goTaskList(row) {
			let start = this.$moment(this.ruleForm.date).format('yyyy-MM-DD') + ' 00:00:00'
			let end = this.$moment(this.ruleForm.date).format('yyyy-MM-DD') + ' 23:59:59'
			const { href } = this.$router.resolve({
				path: '/tasklist',
				query: { shop_id: row.shop_id, shop_name: row.shop_name, start, end }
			})
			window.open(href, '_blank')
		},

		cellMouseEnterOut() {
			this.taskList = []
		},

		cancelEecord() {
			for (let key in this.abnormal) {
				this.abnormal[key] = ''
			}
			this.exceptionRecordShow = false
		},

		async saveEecord() {
			try {
				const { reason_id, reason_type, remark, start_date, end_date } = this.abnormal
				if (!reason_id || !reason_type) return this.$message.error('请选择不用工原因！')
				await demandSetRecord({
					id: +this.workRecord.id,
					reason_id: +reason_id,
					reason_type: +reason_type,
					remark,
					start_date,
					end_date
				})
				this.fetchMonitorList()
				this.cancelEecord()
			} catch (err) {
				console.log(err)
			}
		},

		// 去下单
		goAddOrder(row) {
			const { href } = this.$router.resolve({
				path: '/roleAdd',
				query: { shop_name: row.shop_name, shop_id: row.shop_id, shop_sn: row.shop_sn }
			})
			window.open(href, '_blank')
		},

		// 获取到推荐数据，填充到表单
		async record(row) {
			this.workRecord = row
			this.abnormal.start_date = row.apply_time
			this.abnormal.end_date = row.apply_time
			// 记录过
			if (row.reason_id != 0) {
				this.abnormal.reason_id = row.reason_id
				this.reasonSubsetList = this.reasonList.find(x => x.id == row.reason_id).list
				this.abnormal.reason_type = row.reason_type
				this.abnormal.remark = row.remark
			}

			this.exceptionRecordShow = true
		},

		shearchBtn() {
			// 搜索
			this.pageNum = 1
			this.fetchMonitorList()
		},

		async resetBtn() {
			//重置
			await this.resetData() //重置请求数据
			this.fetchMonitorList()
		},

		async resetData() {
			//重置请求数据
			this.pageNum = 1

			// 重置代理商
			this.agent_reset += 1

			for (let key in this.ruleForm) {
				if (!key == 'agent_id') this.ruleForm[key] = ''
			}
			this.ruleForm.type = '2'
			this.ruleForm.date = this.date(1)
			this.areaList = []

			this.changeSelectCity()
		},
		//店铺的自动完成
		querySearch(queryString, cb) {
			var restaurants = this.shopList
			var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
			// 调用 callback 返回建议列表的数据
			cb(results)
		},
		createFilter(queryString) {
			return restaurant => {
				return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
			}
		},
		handleSelect(item) {
			this.ruleForm.shop_id = item.id
			this.ruleForm.shop_sn = item.shop_sn
		},
		//分页组件->子组件传值
		onChildValue(item) {
			this.pageNum = item[0]
			this.pageSizeNow = item[1]
			this.fetchMonitorList()
		},
		//跳转店铺列表
		shopLists(row) {
			const { href } = this.$router.resolve({
				path: '/shopList',
				query: { shop_name: row.shop_name, shop_id: row.shop_id }
			})
			window.open(href, '_blank')
		},

		//全选-取消全选商圈
		selectAllArea() {
			let arr = []
			this.areaList.forEach(item => {
				arr.push(`${item.id}|${item.area_name}`)
			})
			if (this.areaStatus == true) {
				this.area_arr = arr
			} else {
				this.area_arr = []
			}
			this.areaStatus = !this.areaStatus
		}
	},
	filters: {
		dateshear: function (value) {
			value = value.substr(5, 5).trim()
			return value
		}
	}
}
</script>

<style scoped>
.auditCentent .labels {
	min-height: 100px;
}
.auditCentent .labels .labels_label {
	float: left;
	cursor: pointer;
}
.check_label {
	background: var(--purple4);
	color: #fff;
	border: none;
}
.pdf {
	width: 860px;
	height: 600px;
}
.main_user {
	background: var(--zfy-red);
	color: #fff;
	text-decoration: none;
	padding: 2px 4px;
	border-radius: 4px;
}

.cursor {
	cursor: pointer;
}

.add-order {
	position: relative;
}

.add-order-item {
	border: 1px solid #ececec;
	border-radius: 8px;
	padding: 10px 0;
	margin-bottom: 20px;
	clear: both;
	overflow: hidden;
	position: relative;
}

.del-order-item {
	position: absolute;
	right: 8px;
	top: 40%;
}

.add-order-btn {
	position: absolute;
	left: 150px;
	top: 15px;
}

.dis-order-item .el-select {
	width: 285px;
}

.dis-order-textarea {
	margin-right: 27px;
}

.under-person-num {
	cursor: pointer;
	color: var(--blue1);
	text-decoration: underline;
}

.monitor-types {
	margin-left: 10px;
	margin-bottom: 10px;
}
.monitor-types .button {
	width: 120px;
}
.dialog-layout {
	line-height: 40px;
	color: #222222;
}
.dialog-layout .label-name {
	width: 110px;
	color: #999999;
	text-align: right;
}
.flex-container {
	display: -webkit-flex;
	display: flex;
}
.new-shop {
	padding: 0 5px;
	background: var(--red3);
	color: var(--white);
	border-radius: 2px;
}
</style>
<style>
.add-order .el-form-item {
	width: 44%;
	margin-bottom: 10px;
}

.add-order .el-form-item__content {
	width: 140px;
}

.add-order .el-input__inner {
	width: 140px;
	padding: 0 30px;
	border-radius: 0 !important;
}

.add-order .el-date-editor {
	width: 140px !important;
}

.add-order .el-input-number {
	width: 140px;
}

.add-order .add-order-textarea {
	width: calc(100% - 88px) !important;
	display: flex;
	margin-left: 10px;
}

.add-order .add-order-textarea .el-form-item__content {
	width: 100% !important;
}

.dis-order-date .el-date-editor {
	width: 285px !important;
}

.dis-order-date .el-date-editor .el-range__icon,
.dis-order-date .el-date-editor .el-range-separator {
	line-height: 22px;
}

.demand-monitoring .tableMaxBox .el-date-editor.el-input,
.demand-monitoring .tableMaxBox .el-date-editor.el-input__inner,
.demand-monitoring .tableMaxBox .el-select {
	width: 140px;
	margin-right: 10px;
}
.demand-monitoring .el-textarea {
	width: 300px;
}
</style>



// WEBPACK FOOTER //
// src/components/shop/ShopMonitoring.vue